package com.xhwl.logistics.strategy.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.logistics.bo.cent.VehicleIntegratedConfigBO;
import com.xhwl.logistics.bo.manipulate.VehicleSyncBO;
import com.xhwl.logistics.constant.FuShiConstant;
import com.xhwl.logistics.converter.mapstruct.PaySourceConverter;
import com.xhwl.logistics.entity.VehicleCar;
import com.xhwl.logistics.entity.VehiclePassage;
import com.xhwl.logistics.entity.VehiclePayRecord;
import com.xhwl.logistics.service.cent.IProjectService;
import com.xhwl.logistics.service.impl.VehicleAccessRecordServiceImpl;
import com.xhwl.logistics.service.impl.VehiclePassageServiceImpl;
import com.xhwl.logistics.service.impl.VehiclePayRecordServiceImpl;
import com.xhwl.logistics.strategy.IVehicleParkingLotSyncHandler;
import com.xhwl.logistics.util.DateFormatUtil;
import com.xhwl.logistics.util.HttpUtils;
import com.xhwl.logistics.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;


@Slf4j
//@Service
public class VehicleParkingLotFuShiSyncHandlerImpl implements IVehicleParkingLotSyncHandler {

    /**
     * 富士所用常量
     */
    private static final Integer normal_access = 1;
    private static final Integer car_in = 0;
    private static final Integer car_out = 1;

    @Autowired
    private VehicleAccessRecordServiceImpl vehicleAccessRecordService;

    @Autowired
    private VehiclePassageServiceImpl vehiclePassageService;

    @Autowired
    private IProjectService projectService;

    @Autowired
    private VehiclePayRecordServiceImpl vehiclePayRecordService;

    @Override
    public void syncPayRecord(VehicleIntegratedConfigBO vehicleIntegratedConfigBO, VehicleSyncBO vehicleSyncBO) {
        String host = vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getHost();
        checkSupplierConfigDTO(vehicleIntegratedConfigBO);
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("PageSize", 1000);
        paramMap.put("CurrentPage", 1);
        paramMap.put("OrderBy", "id");
        paramMap.put("OrderType", true);
        paramMap.put("where", String.format("TollTimes>='%S'", DateFormatUtil.date2Str(new Date((System.currentTimeMillis() - 300000)), "yyyy-MM-dd HH:mm:ss")));
        String json = JSON.toJSONString(paramMap);
        Map<String, String> headerMap = new HashMap<>();
        JSONObject jsonResult = HttpUtils.doPost(host + FuShiConstant.getTollRecord, json, headerMap);

        Map parkingLotMap = JSONObject.toJavaObject(jsonResult, Map.class);
        Object data = parkingLotMap.get("Records");
        List<Map> maps = JSON.parseArray(data.toString(), Map.class);
        List<VehiclePayRecord> vehiclePayRecords = new ArrayList<>();
        maps.forEach(map -> {
            VehiclePayRecord vehiclePayRecord = new VehiclePayRecord();
            vehiclePayRecord.setPayRecordId(String.valueOf(map.get("ID")));

            vehiclePayRecord.setAccessRecordId((String) map.get("ParkingId"));
            vehiclePayRecord.setPaidMoney(((Integer) map.get("CashAmount")) * 100);
            vehiclePayRecord.setFreeMoney(((Integer) map.get("FreeAmount")) * 100);
            vehiclePayRecord.setTotalMoney(((Integer) map.get("TranAmount")) * 100);
            vehiclePayRecord.setPayMethod(PaySourceConverter.converterFromFuShi((Integer) map.get("TollType")));
            if (map.get("TollTime") != null) {
                vehiclePayRecord.setPayTime(DateFormatUtil.stringDate2Date((String) map.get("TollTime"), "yyyy-MM-dd'T'HH:mm:ss"));
            }
            vehiclePayRecord.setParkId(vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getParkId());
            if (map.get("InTime") != null) {
                vehiclePayRecord.setEnterTime(DateFormatUtil.stringDate2Date((String) map.get("InTime"), "yyyy-MM-dd'T'HH:mm:ss"));
            }
            vehiclePayRecord.setPlateNumber((String) map.get("TokenId"));
            vehiclePayRecord.setProjectId(vehicleSyncBO.getProjectId());
            vehiclePayRecords.add(vehiclePayRecord);
        });
        vehiclePayRecordService.saveBatch(vehiclePayRecords);
    }
//
//    @Override
//    public void syncAccessRecord(VehicleIntegratedConfigBO vehicleIntegratedConfigBO, VehicleSyncBO vehicleSyncBO) {
//
//
//        ProjectQuery projectQuery = new ProjectQuery();
//        projectQuery.withId(vehicleSyncBO.getProjectId());
//        Project project = projectService.getOne(projectQuery, null);
//
//        if (project == null)
//            throw new BusinessException("未获取到项目信息");
//
//        List<VehicleAccessRecord> vehicleAccessRecords = new ArrayList<>();
//
//        String host = vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getHost();
//        checkSupplierConfigDTO(vehicleIntegratedConfigBO);
//        Map<String, Object> paramInMap = new HashMap<>();
//        paramInMap.put("PageSize", 1000);
//        paramInMap.put("CurrentPage", 1);
//        paramInMap.put("OrderBy", "id");
//        paramInMap.put("OrderType", true);
//        paramInMap.put("where", String.format("InTime>='%S'", DateFormatUtil.date2Str(new Date((System.currentTimeMillis() - 300000)), "yyyy-MM-dd HH:mm:ss")));
//        String jsonIn = JSON.toJSONString(paramInMap);
//        Map<String, String> headerMap = new HashMap<>();
//
//
//        JSONObject jsonInResult = HttpUtils.doPost(host + FuShiConstant.getInVehicle, jsonIn, headerMap);
//
//
//        Map parkingLotInMap = JSONObject.toJavaObject(jsonInResult, Map.class);
//        if (parkingLotInMap != null) {
//            Object dataIn = parkingLotInMap.get("Records");
//            if (dataIn != null) {
//                List<Map> mapsIn = JSON.parseArray(dataIn.toString(), Map.class);
//                if (mapsIn != null) {
//                    mapsIn.forEach(map -> {
//                        VehicleAccessRecord vehicleAccessRecordAdd = new VehicleAccessRecord();
//                        vehicleAccessRecordAdd.setProjectId(project.getId());
//                        vehicleAccessRecordAdd.setProjectCode(project.getCode());
//                        vehicleAccessRecordAdd.setProjectName(project.getName());
//                        vehicleAccessRecordAdd.setPlateNumber((String) map.get("TokenNo"));
////                        List<VehicleCar> vehicleCarList = vehicleCarService.list(conditionForCar((String) map.get("TokenNo"), project.getId()));
////                        if (!vehicleCarList.isEmpty()) {
////                            vehicleAccessRecordAdd.setOwnerName(vehicleCarList.get(0).getOwnerName());
////                            vehicleAccessRecordAdd.setOwnerPhone(vehicleCarList.get(0).getOwnerPhone());
////                            vehicleAccessRecordAdd.setCardType(vehicleCarList.get(0).getCardType());
////                        } else {
//                            // TODO: 2023/4/10
////                vehicleAccessRecordAdd.setCardType(TcmName);
////                        }
//
//                        vehicleAccessRecordAdd.setExitPictureUrl((String) map.get("InPicture"));
//                        if (map.get("InTime") != null) {
//                            vehicleAccessRecordAdd.setExitTime(DateFormatUtil.stringDate2Date((String) map.get("InTime"), "yyyy-MM-dd'T'HH:mm:ss"));
//                        }
//                        vehicleAccessRecordAdd.setExitType(normal_access);
//                        VehiclePassage vehiclePassage = vehiclePassageService.getOne(conditionPassage((String) map.get("InLaneId"), project.getId()));
//                        if (vehiclePassage != null) {
//                            vehicleAccessRecordAdd.setExitPassageName(vehiclePassage.getPassageName());
//                            vehicleAccessRecordAdd.setExistPassageId(vehiclePassage.getId());
//                        }
//                        vehicleAccessRecordAdd.setRecordId(String.valueOf(map.get("ID")));
//                        vehicleAccessRecordAdd.setStatus(car_in);
//                        vehicleAccessRecordAdd.setParkId(vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getParkId());
//                        vehicleAccessRecords.add(vehicleAccessRecordAdd);
//                    });
//                }
//            }
//        }
//
//
//        Map<String, Object> paramOutMap = new HashMap<>();
//        paramOutMap.put("PageSize", 1000);
//        paramOutMap.put("CurrentPage", 1);
//        paramOutMap.put("OrderBy", "id");
//        paramOutMap.put("OrderType", true);
//        paramOutMap.put("where", String.format("OutTime>='%S'", DateFormatUtil.date2Str(new Date((System.currentTimeMillis() - 300000)), "yyyy-MM-dd HH:mm:ss")));
//        String jsonOut = JSON.toJSONString(paramOutMap);
//        JSONObject jsonOutResult = HttpUtils.doPost(host + FuShiConstant.getOutVehicle, jsonOut, headerMap);
//
//        Map parkingLotOutMap = JSONObject.toJavaObject(jsonOutResult, Map.class);
//        if (parkingLotOutMap != null) {
//            Object dataOut = parkingLotOutMap.get("Records");
//            if (dataOut != null) {
//                List<Map> mapsOut = JSON.parseArray(dataOut.toString(), Map.class);
//                if (mapsOut != null) {
//                    mapsOut.forEach(map -> {
//                        VehicleAccessRecord vehicleAccessRecordAdd = new VehicleAccessRecord();
//                        vehicleAccessRecordAdd.setProjectId(project.getId());
//                        vehicleAccessRecordAdd.setProjectCode(project.getCode());
//                        vehicleAccessRecordAdd.setProjectName(project.getName());
//                        vehicleAccessRecordAdd.setPlateNumber((String) map.get("TokenNo"));
//
////                        List<VehicleCar> vehicleCarList = vehicleCarService.list(conditionForCar((String) map.get("TokenNo"), project.getId()));
////                        if (!vehicleCarList.isEmpty()) {
////                            vehicleAccessRecordAdd.setOwnerName((String) map.get("TokenNo"));
////                            vehicleAccessRecordAdd.setOwnerPhone(vehicleCarList.get(0).getOwnerPhone());
////                            vehicleAccessRecordAdd.setCardType(vehicleCarList.get(0).getCardType());
////                        } else {
//
////
////                        }
////                        vehicleAccessRecordAdd.setCardType(VehicleCardTypeEnum.toVehicleCardTypeEnumByFuShi(map.get("")));
//                        vehicleAccessRecordAdd.setEnterPictureUrl((String) map.get("InPicture"));
//                        vehicleAccessRecordAdd.setEnterTime(DateFormatUtil.stringDate2Date((String) map.get("InTime"), "yyyy-MM-dd'T'HH:mm:ss"));
//                        vehicleAccessRecordAdd.setEnterType(normal_access);
//                        vehicleAccessRecordAdd.setExitPictureUrl((String) map.get("OutPicture"));
//                        vehicleAccessRecordAdd.setExitTime(DateFormatUtil.stringDate2Date((String) map.get("OutTime"), "yyyy-MM-dd'T'HH:mm:ss"));
//                        vehicleAccessRecordAdd.setExitType(normal_access);
//                        VehiclePassage vehiclePassage = vehiclePassageService.getOne(conditionPassage((String) map.get("OutLaneId"), project.getId()));
//                        if (vehiclePassage != null) {
//                            vehicleAccessRecordAdd.setExitPassageName(vehiclePassage.getPassageName());
//                            vehicleAccessRecordAdd.setExistPassageId(vehiclePassage.getId());
//                        }
//                        vehicleAccessRecordAdd.setRecordId(String.valueOf(map.get("ID")));
//                        vehicleAccessRecordAdd.setStatus(car_out);
//                        vehicleAccessRecordAdd.setParkId(vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getParkId());
//                        vehicleAccessRecords.add(vehicleAccessRecordAdd);
//                    });
//                }
//            }
//        }
//        vehicleAccessRecordService.saveBatch(vehicleAccessRecords);
//    }

    private void checkSupplierConfigDTO(VehicleIntegratedConfigBO vehicleIntegratedConfigBO) {
        if (vehicleIntegratedConfigBO == null || vehicleIntegratedConfigBO.getVehicleParkingInfoBO() == null) {
            throw new BusinessException("配置信息无vehicleIntegratedConfigBO");
        }
        if (StringUtils.isBlank(vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getHost())) {
            throw new BusinessException("配置信息无host,请到供应商配置平台配置");
        }
    }

    private Wrapper<VehiclePassage> conditionPassage(String thirdPassageId, Integer projectId) {
        LambdaQueryWrapper<VehiclePassage> vehiclePassageLambdaQueryWrapper = new LambdaQueryWrapper<>();
        return vehiclePassageLambdaQueryWrapper.eq(VehiclePassage::getProjectId, projectId)
                .eq(VehiclePassage::getThirdPassageId, thirdPassageId);
    }

    private Wrapper<VehicleCar> conditionForCar(String plateNumber, Integer projectId) {
        LambdaQueryWrapper<VehicleCar> vehicleCarLambdaQueryWrapper = new LambdaQueryWrapper<>();
        return vehicleCarLambdaQueryWrapper.eq(VehicleCar::getPlateNumber, plateNumber)
                .eq(VehicleCar::getProjectId, projectId)
                .orderByDesc(VehicleCar::getCreatedAt);
    }
}
